<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #form-age="{ model, field }">
        <a-form-item>
          <a-input placeholder="最小年龄" type="ge" v-model:value="min" style="width: calc(50% - 15px)" @change="ageChange(model, field)"></a-input>
          <span>~</span>
          <a-input placeholder="最大年龄" type="le" v-model:value="max" style="width: calc(50% - 15px)" @change="ageChange(model, field)"></a-input>
        </a-form-item>
      </template>
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd">新增</a-button>
        <a-upload name="file" :showUploadList="false" :customRequest="(file) => handleImportXls(file, getImportUrl, reload)">
          <a-button preIcon="ant-design:import-outlined" type="primary">导入</a-button>
        </a-upload>
        <a-button preIcon="ant-design:export-outlined" type="primary" @click="handleExportXls('单表示例', getExportUrl, exportParams)">导出</a-button>

        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="openTab">打开Tab页</a-button>
        <a-button preIcon="ant-design:import-outlined" type="primary" @click="handleImport">弹窗导入</a-button>

        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleFeign">测试Feign</a-button>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleFeignUrl">测试Feign-Url</a-button>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleDate">测试date</a-button>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleRoute">测试路由</a-button>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleRoute404">测试路由404</a-button>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleLocal">测试本地缓存</a-button>
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleI18n">测试i18n</a-button>

        <a-dropdown v-if="checkedKeys.length > 0">
          <a-button>批量操作
            <Icon icon="ant-design:down-outlined"></Icon>
          </a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getActions(record)" />
      </template>
    </BasicTable>
    <DemoModal @register="registerModal" @success="reload" :isDisabled="isDisabled" />
    <JImportModal @register="registerModalJimport" :url="getImportUrl" online />
  </div>
</template>
<script lang="ts" setup>
import { ref, unref, reactive, toRaw, watch, computed } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import DemoModal from './demoModal.vue';
// import { list, deleteOne, deleteBatch, getExportUrl, getImportUrl, getTenantById, getDate, getUrlMsg } from './demo.api';
import { list, deleteOne, deleteBatch, getExportUrl, getImportUrl, getTenantById, getDate, getUrlMsg } from '/@/common/api/testApi';
import { columns, searchFormSchema } from './demo.data';
import JImportModal from '/@/components/Form/src/jeecg/components/JImportModal.vue';
import { useMethods } from '/@/hooks/system/useMethods';
import { useGo } from '/@/hooks/web/usePage';
import { filterObj } from '/@/utils/common/compUtils';
import { setAuthCache ,getAuthCache} from '/@/common/util/localCache';
import { useI18n } from '/@/hooks/web/useI18n';
import { useRouter } from 'vue-router'; // 路由跳转
import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createConfirm, createMessage: $message } = useMessage(); // 解构

const { t } = useI18n();
const router = useRouter();
const go = useGo();
const checkedKeys = ref<Array<string | number>>([]);
const [registerModal, { openModal }] = useModal();
const [registerModalJimport, { openModal: openModalJimport }] = useModal();
const { handleExportXls, handleImportXls } = useMethods();
const min = ref();
const max = ref();
const isDisabled = ref(false);

const [registerTable, { reload, setProps }] = useTable({
  title: '单表示例',
  api: list,
  columns,
  formConfig: {
    //labelWidth: 120,
    schemas: searchFormSchema,
    fieldMapToTime: [['birthday', ['birthdayBegin', 'birthdayEnd'], 'YYYY-MM-DD']],
    fieldMapToNumber: [['age', ['ageBegin', 'ageEnd']]],
    autoAdvancedCol: 3,
    actionColOptions: {
      style: { textAlign: 'left' },
    },
  },
  //自定义默认排序
  defSort: {
    column: 'createTime,sex',
    order: 'desc',
  },
  striped: true,
  useSearchForm: true,
  showTableSetting: true,
  clickToRowSelect: false,
  bordered: true,
  showIndexColumn: false,
  tableSetting: { fullScreen: true },
  canResize: false,
  rowKey: 'id',
  actionColumn: {
    width: 180,
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: undefined,
  },
});
/**
 * 选择列配置
 */
const rowSelection = {
  type: 'checkbox',
  columnWidth: 40,
  selectedRowKeys: checkedKeys,
  onChange: onSelectChange,
};

function handleImport() {
  openModalJimport(true);
}

const exportParams = computed(() => {
  let paramsForm = {};
  if (checkedKeys.value && checkedKeys.value.length > 0) {
    paramsForm['selections'] = checkedKeys.value.join(',');
  }
  return filterObj(paramsForm)
})
/**
 * 操作列定义
 * @param record
 */
function getActions(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}

/**
 * 选择事件
 */
function onSelectChange(selectedRowKeys: (string | number)[]) {
  console.log("checkedKeys------>", checkedKeys)
  checkedKeys.value = selectedRowKeys;
}

/**
 * 新增事件
 */
function handleAdd() {
  isDisabled.value = false;
  openModal(true, {
    isUpdate: false,
  });
}

/**
 * 测试feign事件
 */
async function handleFeign() {
  let values = await getTenantById({ id: '1000' });
  $message.info(values.name);
}

/**
 * 测试feign事件
 */
async function handleFeignUrl() {
  let values = await getUrlMsg({});
  $message.info(JSON.stringify(values));
}

/**
 * 测试日期
 */
async function handleDate() {
  let values = await getDate({});
  $message.info(JSON.stringify(values));
}

/**
 * 测试路由
 */
async function handleRoute() {
  router.replace(`/system/user`);
  // router.replace({ path: `/system/user`});
}

/**
 * 测试路由-404
 */
async function handleRoute404() {
  router.replace({ path: `/zhc/404`, query: { tableName: '1234' } });
}

/**
 * 测试缓存
 */
async function handleLocal() {
  $message.info('本地缓存');

  setAuthCache('4444444444', '2323232323');
  let sss = getAuthCache('4444444444');
  // cls.remove('4444444444');
  // debugger
  $message.info('本地缓存' + sss);
}
/**
 * 测试i18n
 */
async function handleI18n() {
  let msg = t('sys.api.timeoutMessage');
  $message.info('测试i18n'+msg);
}



/**
 * 编辑事件
 */
function handleEdit(record) {
  isDisabled.value = false;
  openModal(true, {
    record,
    isUpdate: true,
  });
}

/**
 * 详情页面
 */
function handleDetail(record) {
  isDisabled.value = true;
  openModal(true, {
    record,
    isUpdate: true,
  });
}

/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id });
  handleSuccess();
}

/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  createConfirm({
    iconType: 'warning',
    title: '确认删除',
    content: '是否删除选中数据',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      await deleteBatch({ ids: checkedKeys.value });
      handleSuccess();
    }
  });
}

/**
 * 成功回调
 */
function handleSuccess() {
  (checkedKeys.value = []) && reload();
}

/**
 * 年龄修改事件
 */
function ageChange(model, field) {
  model[field] = [unref(min), unref(max)];
}

/**
 * 打开tab页面
 */
function openTab() {
  go(`/comp/jeecg/basic`);
}

const customSearch = ref(false);
const queryParam = reactive({
  name: '',
  ageBegin: '',
  ageEnd: '',
  sex: '',
  id: '',
});
watch(customSearch, () => {
  setProps({ useSearchForm: !unref(customSearch) });
});
</script>
<style lang="less" scoped>
.jeecg-basic-table-form-container {
  .table-page-search-submitButtons {
    display: block;
    // margin-bottom: 24px;
    white-space: nowrap;
  }
}
</style>
